<template>
  <!-- 按钮 -->
  <div class="btn-config">
    <!-- <BtnConfig :btn-configs="btnOption[btnType]" @propClick="handleClick" /> -->
    <FooterButton
      :button-disable="btnOption[btnType]"
      class="btn-init"
      @handleNext="handleClick('doNext')"
      @handlereDeploy="handleClick('doReassign')"
      @handleBack="handleClick('doBack')"
      @handleClose="handleClick('doClose')"
    />
    <!-- 下一步  -->
    <next-page
      v-if="nextPageVisible"
      ref="nextPage"
      :visible.sync="nextPageVisible"
      :activity-inst-id="workFlowData.activityInstID"
      :process-inst-id="workFlowData.processInstID"
      :activity-def-id="workFlowData.activityDefID"
      :process-def-name="workFlowData.processDefName"
      :prj-id="workFlowData.prjId"
      :prj-stage="workFlowData.prjStage"
      @doNextEntity="nextPageRes"
    />
    <!--  回退 -->
    <Back-page
      v-if="backPageVisible"
      ref="backPage"
      :visible.sync="backPageVisible"
      :process-inst-id="workFlowData.processInstID"
      :act-inset-id="workFlowData.actInsetId"
      @doReturn="backPageRes"
    />
    <!-- 转派 -->
    <TransferPage
      v-if="transferPageVisible"
      :visible.sync="transferPageVisible"
      :process-inst-id="workFlowData.processInstID"
      :org-id="workFlowData.orgId"
      :org-code="workFlowData.orgCode"
      @selected="selected"
      @redeployEntity="redeployEntity"
    />
  </div>
</template>

<script>
import FooterButton from '@/components/footer/details'
import { finishbtnOptionA, finishbtnOptionB } from '../index.js'
import {
    getWFWorkItem
} from '@/api/actualBudget/index'
import {
    settlementProcess,
    getNextBackVerfiation,
    nextStrengthCheck
} from '@/api/settlement/balanceSettlement.js'
import { getPrjDetail } from '@/api/actualBudget'
// import BtnConfig from '@/components/basic/btnConfig.vue'
import NextPage from '@/views/balance/components/txNextPage'
import BackPage from '@/components/nextPerson/BackPage'
import TransferPage from '@/components/nextPerson/ReassignPageNew.vue'
export default {
    name: 'ButtonProcess',
    components: {
        // BtnConfig,
        NextPage,
        BackPage,
        TransferPage,
        FooterButton
    },
    props: {
        paramsObj: {
            type: Object,
            default: () => ({ })
        },
        nextBtnDilogShow: {
            type: Boolean
        },
        isSaveTrue: {
            type: Function,
            require: true,
            default: null
        },
        attachmentInfo:{
            type: Object,
            default: () => ({ })
        }
    },
    data() {
        return {
            btnType: 'A',
            // 按钮类型
            btnOption: {
                'A': finishbtnOptionA,
                'B': finishbtnOptionB
            },
            nextPageVisible: false, // 下一步弹框显示
            backPageVisible: false, // 回退弹框显示
            transferPageVisible: false,
            workFlowData: {
                activityInstID: null,
                processInstID: null, // 下一步 && 回退
                activityDefID: null,
                actInsetId: null, // 下一步 && 回退
                processDefName: '',
                orgId: '',
                orgCode: '',
                prjId: '',
                prjStage: 'Q'
            },
            lcList: '', // 基本信息1
            basicList: '', // 基本信息2
            urlList: {}// 接受getWFWorkItem 接口返回的数据
        }
    },
    created() {
        this.getCurrentNode()
    },
    methods: {
        // 下一步/回退第二层校验
        async nextVerfict(fun, params) {
            const { code } = await getNextBackVerfiation(params)
            if (+code === 200) {
                this[fun]()
            }
        },
        async cancelnextVerify(fun, params) {
            if (this.attachmentInfo.isNewbusiness === '1' && ['29','25'].includes(this.attachmentInfo.buildModes) ) {
                await this.nextVerfict(fun, params)
                return Promise.reject()
            }
        },
        // 下一步第一层校验
        async nextFirstVerfit(fun, params) {
            const { prjId } = this.paramsObj
            // 接口参数
            const nextParams = {
                prjId: prjId,
                prjStage: 'Q'
            }
            await this.cancelnextVerify(fun, params)
            // 首先第一层校验判断强弱
            const { code, data } = await nextStrengthCheck(nextParams)
            const { check, msg, confirm } = data
            if (+code === 200) {
                // 判断是否存在强若校验
                if (!check) {
                    // 强校验
                    if (confirm === 'T') {
                        // 强校验禁止下一步
                        setTimeout(() => {
                            this.$message({
                                // 将html化
                                dangerouslyUseHTMLString: true,
                                message: msg,
                                type: 'warning'
                            })
                        }, 500)
                    } else {
                        // 若校验 是可以下一步/否不可以
                        setTimeout(() => {
                            this.$confirm(`${msg}<br/>是否继续操作?`, '系统提示', {
                                dangerouslyUseHTMLString: true,
                                confirmButtonText: '是',
                                cancelButtonText: '否',
                                cancelButtonClass: 'pms-zr-button',
                                confirmButtonClass: 'pms-zr-button-primary',
                                type: 'warning'
                            }).then(() => {
                                this.nextVerfict(fun, params)
                            }).catch(() => {
                                console.log('cancel')
                            })
                        }, 500)
                    }
                } else {
                    this.nextVerfict(fun, params)
                }
            }
        },
        // 按钮回调方法
        async handleClick(fun, row) {
            // 是否真的修改过数据
            const finishStatus = this.isSaveTrue()
            // 判断物资是否保存了
            const materia = JSON.parse(sessionStorage.getItem('recordIndex'))
            // 判断服务是否保存了
            const services = JSON.parse(sessionStorage.getItem('rocordId'))
            const { adjustId, processInstId, prjId } = this.paramsObj
            const params = {
                adjustId: adjustId,
                prjId: prjId,
                workFlowFlag: fun,
                processInstId: processInstId
            }
            // 如果是下一步需要先保存
            if (fun === 'doNext') {
               // 1.判断是否保存了 如果没有保存则首先进行保存
               if (finishStatus && (materia?.length > 0 || services?.length > 0)) {
                    this.$emit('nextSave')
                } else {
                    sessionStorage.removeItem('recordIndex')
                    sessionStorage.removeItem('rocordId')
                    // 2.保存以后调用第一层强弱校验 如果通过则进行第二层校验 否则停在原地 并提示信息
                    this.nextFirstVerfit(fun, params)
                }
            } else {
                // 回退强弱校验通过以后才可以调用这个下一层校验
                if (fun === 'doBack') {
                    // 下一步校验看是否通过通过才能打开弹框
                    this.nextVerfict(fun, params)
                } else {
                    this[fun]()
                }
            }
        },
        // 下一步按钮主方法
        async doNext() {
            const { prjId } = this.paramsObj
            // 赋值打开下一步弹框
            this.workFlowData = {
                activityInstID: this.lcList.activityInstID,
                processInstID: this.lcList.processInstID,
                activityDefID: this.lcList.activityDefID,
                processDefName: this.lcList.processInstName,
                prjId: prjId,
                prjStage: 'Q'
            }
            this.nextPageVisible = true
        },
        // 退回按钮主方法
        async doBack() {
            this.workFlowData = {
                processInstID: this.lcList.processInstID,
                actInsetId: this.lcList.activityInstID
            }
            this.backPageVisible = true
        },
        // 转派按钮主方法
        async doReassign() {
            // 赋值打开下一步弹框
            this.workFlowData = {
                processInstID: this.lcList.processInstID,
                orgCode: this.basicList.orgCode,
                orgId: this.basicList.orgId
            }
            this.transferPageVisible = true
        },
        // 关闭页面主方法
        doClose(node) {
            const enumTitle = {
                1: '提交成功',
                2: '提交成功',
                3: '转派成功'
            }
            // 1.下一步：提交成功 回退：提交成功 转派：转派成功 关闭：无二次确认弹窗
            if (node) {
                this.$alert(`${enumTitle[node]}`, '系统提示', {
                    confirmButtonText: '确认',
                    cancelButtonClass: 'pms-zr-button',
                    callback: action => {
                        window.opener = null
                        window.open('about:blank', '_top').close()
                    }
                })
            } else {
                window.opener = null
                window.open('about:blank', '_top').close()
            }
        },
        // 获取当前属于哪个节点
        async getCurrentNode() {
            const { workItemId } = this.paramsObj
            if (!workItemId) {
                this.getInitBasicInfo()
                return
            }
            const { code, data } = await getWFWorkItem({ workItemId: workItemId })
            if (+code === 200) {
                this.getInitBasicInfo()
                this.lcList = data
                const { bizObject } = data
                // 判断当前属于那个节点 显示不同的按钮
                if (bizObject.nodeCode === 'sett_01') {
                    this.btnType = 'A'
                } else {
                    this.btnType = 'B'
                }
            }
        },
        // 获取 orgid orgCode
        async getInitBasicInfo() {
            const { prjId } = this.paramsObj
            if (!prjId) {
                return
            }
            const { code, data } = await getPrjDetail({ prjId: prjId })
            if (+code === 200) {
                this.basicList = data
            }
        },
        // 下一步确认回调
        nextPageRes(item) {
            const ifNextVal = '1' // 下一步传 1
            this.nextBackPageRes(item, ifNextVal)
        },
        // 退回确认回调
        async backPageRes(item) {
            const ifNextVal = '2' // 回退传2
            this.nextBackPageRes(item, ifNextVal)
        },
        // 转派确认回调
        redeployEntity(item) {
            const ifNextVal = '3' // 转派传3
            this.nextBackPageRes(item, ifNextVal)
        },
        // 下一步 && 回退 &&转派 确认函数
        async nextBackPageRes(item, ifNextVal) {
            console.log(item, ifNextVal, 'ifNextVal')
            const { prjId, adjustId } = this.paramsObj
            let workFlowFlag = ''
            let messageVal = ''
            // 下一步
            if (ifNextVal === '1') {
                workFlowFlag = 'doNext'
                messageVal = '提交成功'
            } else if (ifNextVal === '2') {
                workFlowFlag = 'doBack'
                messageVal = '回退成功'
            } else {
                workFlowFlag = 'doReassign'
                messageVal = '转派成功'
            }
            const data = {
                adjustId: adjustId,
                prjId: prjId,
                workFlowFlag: workFlowFlag,
                templateId: this.lcList.processDefName,
                nextNodeId: item.nodeId,
                nextNodeName: item?.nodeName,
                workItemId: this.lcList.workItemID,
                opinion: item.opinion,
                userIds: item.userId ? item.userId : item.empId,
                processInstId: this.lcList.processInstID,
                detailId: item?.detailId
            }
            // 调用后端接口
            const finalNextFlow = await settlementProcess(data)
            if (+finalNextFlow.code === 200) {
                // 关闭页面
                this.doClose(ifNextVal)
            }
        },
        // 转派的下拉框
        selected(item) {
            console.log(item)
        }
    }
}

</script>
<style lang="scss" scoped>
.btn-config {
    width: 100%;
    padding: 15px;
    // border: 1px solid #EBEEF5;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20px;

    .btn-init {
        width: 100%;
    }
}

.el-message--error {
    white-space: pre-line
}

// .btn-config ::v-deep .btnBox {
//     display: block;
// }</style>
